{% extends theme_path('admin/base.html') %}

{% block title %}{{ title }}{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="bg-white rounded-lg shadow-sm">
        <div class="px-6 py-4 border-b">
            <h2 class="text-xl font-bold">{{ title }}</h2>
        </div>
        
        <form id="pageForm" method="post" class="p-6" 
              action="{{ url_for('admin.update_custom_page', id=page.id) if page else url_for('admin.add_custom_page') }}">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- 左侧主要内容 -->
                <div class="lg:col-span-2 space-y-6">
                    <!-- 页面标题 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">页面标题</label>
                        <input type="text" name="title" 
                               value="{{ page.title if page else '' }}"
                               required
                               class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>

                    <!-- 页面内容 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">页面内容</label>
                        <textarea id="editor" name="content">{{ page.content|safe if page and page.content else '' }}</textarea>
                        {{ render_tinymce(selector='#editor', height=350) }}
                    </div>

                    <!-- 在内容编辑器下方添加附件库按钮 -->
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mt-6">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-lg font-medium text-gray-900 dark:text-white">附件库</h3>
                            <button type="button" onclick="showFileManager()"
                                    class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                                打开附件库
                            </button>
                        </div>
                    </div>

                    <!-- 自定义字段 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">自定义字段</label>
                        <div id="customFields" class="space-y-4">
                            {% if page and page.fields %}
                                {% for key, value in page.fields.items() %}
                                <div class="flex items-center space-x-4">
                                    <input type="text" name="field_keys[]" value="{{ key }}"
                                           placeholder="字段名"
                                           class="w-1/3 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <input type="text" name="field_values[]" value="{{ value }}"
                                           placeholder="字段值"
                                           class="w-2/3 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                    <button type="button" onclick="removeField(this)"
                                            class="text-red-600 hover:text-red-900">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                        </svg>
                                    </button>
                                </div>
                                {% endfor %}
                            {% endif %}
                        </div>
                        <button type="button" onclick="addField()"
                                class="mt-2 px-4 py-2 text-sm border rounded-lg hover:bg-gray-50">
                            + 添加字段
                        </button>
                    </div>
                </div>

                <!-- 右侧设置 -->
                <div class="space-y-6">
                    <div class="bg-gray-50 rounded-lg p-6 space-y-6">
                        <!-- 页面标识 -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">页面标识</label>
                            <input type="text" name="key" 
                                   value="{{ page.key if page else '' }}"
                                   required
                                   pattern="[A-Za-z0-9_\-]+"
                                   class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <p class="mt-1 text-sm text-gray-500">唯一标识,只能包含字母、数字、下划线和连字符</p>
                        </div>

                        <!-- 模板文件 -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">模板文件</label>
                            <select name="template" required
                                    class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                {% for tpl in templates %}
                                <option value="{{ tpl.path }}"
                                        {% if page and page.template == tpl.path %}selected{% endif %}>
                                    {{ tpl.name }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>

                        <!-- 路由规则 -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">路由规则</label>
                            <input type="text" name="route"
                                   value="{{ page.route if page else '' }}"
                                   placeholder="/custom/[key]"
                                   class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <p class="mt-1 text-sm text-gray-500">留空则使用默认规则 /custom/[key]</p>
                        </div>

                        <!-- 需要登录 -->
                        <div class="flex items-center">
                            <input type="checkbox" name="require_login" id="require_login"
                                   {% if page and page.require_login %}checked{% endif %}
                                   class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="require_login" class="ml-2 text-sm text-gray-700">需要登录</label>
                        </div>

                        <!-- 添加评论开关 -->
                        <div class="flex items-center">
                            <input type="checkbox" name="allow_comment" id="allow_comment"
                                   {% if not page or page.allow_comment %}checked{% endif %}
                                   class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="allow_comment" class="ml-2 text-sm text-gray-700">允许评论</label>
                        </div>

                        <!-- 页面状态 -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">页面状态</label>
                            <select name="status" class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="{{ CustomPage.STATUS_PUBLIC }}" {% if page and page.status == CustomPage.STATUS_PUBLIC %}selected{% endif %}>公开</option>
                                <option value="{{ CustomPage.STATUS_PRIVATE }}" {% if page and page.status == CustomPage.STATUS_PRIVATE %}selected{% endif %}>隐藏</option>
                            </select>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="flex justify-end space-x-4">
                        <a href="{{ url_for('admin.custom_pages') }}"
                           class="px-4 py-2 border rounded-lg hover:bg-gray-50">
                            取消
                        </a>
                        <button type="submit"
                                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                            {{ '保存修改' if page else '创建页面' }}
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
    <!-- 附件库模态框 -->
    <div id="fileManagerModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-5xl max-h-[90vh] overflow-hidden">
                <!-- 模态框头部 -->
                <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
                    <h3 class="text-xl font-bold text-gray-900 dark:text-white">附件库</h3>
                    <button onclick="hideFileManager()" class="text-gray-500 hover:text-gray-700">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>

                <!-- iframe容器 -->
                <div id="fileManagerContainer" class="h-[calc(90vh-80px)]">
                    <!-- iframe将在打开模态框时动态加载 -->
                </div>
            </div>
        </div>
    </div>
<!-- JavaScript 代码保持不变 -->
<script>
function addField() {
    const container = document.getElementById('customFields');
    const fieldDiv = document.createElement('div');
    fieldDiv.className = 'flex items-center space-x-4';
    fieldDiv.innerHTML = `
        <input type="text" name="field_keys[]" placeholder="字段名"
               class="w-1/3 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
        <input type="text" name="field_values[]" placeholder="字段值"
               class="w-2/3 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
        <button type="button" onclick="removeField(this)"
                class="text-red-600 hover:text-red-900">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
        </button>
    `;
    container.appendChild(fieldDiv);
}

function removeField(button) {
    button.closest('div').remove();
}

document.getElementById('pageForm').onsubmit = function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    
    // 获取编辑器内容
    formData.set('content', tinymce.get('editor').getContent());
    
    // 获取自定义字段
    const fields = {};
    const keys = formData.getAll('field_keys[]');
    const values = formData.getAll('field_values[]');
    keys.forEach((key, index) => {
        if (key.trim()) {
            fields[key.trim()] = values[index];
        }
    });
    formData.set('fields', JSON.stringify(fields));
    
    // 获取复选框的值
    const allowComment = document.getElementById('allow_comment').checked;
    formData.set('allow_comment', allowComment.toString());  // 转换为字符串 'true' 或 'false'
    
    // 获取需要登录选项
    formData.set('require_login', document.getElementById('require_login').checked.toString());
    
    // 添加调试日志
    console.log('allow_comment value:', allowComment);
    
    // 获取状态值 - 确保是整数
    const statusSelect = document.querySelector('select[name="status"]');
    formData.set('status', parseInt(statusSelect.value));
    
    // 提交表单
    fetch(this.action, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert(data.error, 'error', '错误');
        } else {
            showAlert(data.message, 'success', '成功');
            setTimeout(() => location.href = '{{ url_for("admin.custom_pages") }}', 500);
        }
    });
};
</script>


    <script>
        let fileManagerLoaded = false;

        function showFileManager() {
            const modal = document.getElementById('fileManagerModal');
            const container = document.getElementById('fileManagerContainer');

            // 如果iframe还没加载过,则加载iframe
            if (!fileManagerLoaded) {
                container.innerHTML = `
            <iframe src="{{ url_for('admin.manage_files', mode='selector') }}"
                    class="w-full h-full border-0"
                    id="fileManagerFrame"></iframe>
        `;
                fileManagerLoaded = true;
            }

            modal.classList.remove('hidden');
        }

        function hideFileManager() {
            const modal = document.getElementById('fileManagerModal');
            modal.classList.add('hidden');
        }

        // 监听来自iframe的消息
        window.addEventListener('message', function(event) {
            if (event.data.type === 'fileSelected') {
                const file = event.data.file;
                const editor = tinymce.get('editor');

                // 直接使用传过来的content内容
                if (file.content) {
                    editor.insertContent(file.content);
                } else {
                    // 降级处理，以防content不存在
                    if (file.file_type && file.file_type.startsWith('image/')) {
                        editor.insertContent(`<img src="${file.url}" alt="${file.name}" style="max-width:100%;">`);
                    } else if (file.file_type && file.file_type.startsWith('video/')) {
                        editor.insertContent(`<video controls style="max-width:100%;"><source src="${file.url}" type="${file.file_type}">您的浏览器不支持视频标签</video>`);
                    } else if (file.file_type && file.file_type.startsWith('audio/')) {
                        editor.insertContent(`<audio controls><source src="${file.url}" type="${file.file_type}">您的浏览器不支持音频标签</audio>`);
                    } else {
                        editor.insertContent(`<a href="${file.url}" target="_blank">${file.name}</a>`);
                    }
                }

                // 插入后关闭模态框
                hideFileManager();
            }
        });

        // 点击模态框背景关闭
        document.getElementById('fileManagerModal').addEventListener('click', function(e) {
            if (e.target === this) {
                hideFileManager();
            }
        });
    </script>
{% endblock %} 